import PaymentManager from '../../utils/paymentManager'; // 请根据实际路径调整

// 查询订单支付状态
async function queryOrderStatus(orderNo) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: 'https://visa.goldenholiday.com/api/miniapp/admin/order/pageinfo',
      method: 'GET',
      data: { orderNo },
      header: { 'content-type': 'application/json', 'token': wx.getStorageSync('token') },
      success: (res) => {
        if (res.data && res.data.data && res.data.data.records && res.data.data.records.length > 0) {
          resolve(res.data.data.records[0].orderStatus);
        } else {
          resolve(null);
        }
      },
      fail: reject
    });
  });
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// 生成东八区本地时间字符串（不带Z，格式为 yyyy-MM-dd'T'HH:mm:ss.SSS）
function getLocalISOString() {
  const date = new Date();
  const pad = n => n.toString().padStart(2, '0');
  const ms = date.getMilliseconds().toString().padStart(3, '0');
  return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${ms}`;
}

Page({
  data: {
    userName: '',
    activeTab: 'electronic',
    electronicStatus: 'pending',
    electronicStatusText: '待完成',
    paperStatus: 'pending',
    paperStatusText: '待完成',
    dateStatus: 'completed',
    dateStatusText: '已完成',
    electronicDocuments: [],
    paperDocuments: [],
    dates: [],
    showOrderModal: false,
    showOtherPaymentModal: false,
    orderNo: '',
    paymentCode: ''
  },

  // 修改 onLoad 方法
  onLoad(options) {
    this.paymentManager = new PaymentManager();
    // 只在有 eventChannel 的情况下初始化
    const eventChannel = this.getOpenerEventChannel();
    if (eventChannel?.on) {
      eventChannel.on('acceptApplicantData', this._handleApplicantData.bind(this));
    }
  },
  // 添加日期选择处理方法
  onDateChange(e) {
    const index = e.currentTarget.dataset.index;
    const selectedOption = this.data.dates[index].options[e.detail.value];
    this.setData({
      [`dates[${index}].selected`]: selectedOption
    }, () => {
      // 更新日期状态
      this.setData({
        dateStatus: 'completed',
        dateStatusText: '已完成'
      });
    });
  },

  _handleApplicantData(data) {
    const { applicants, price, cityInfo, visaInfo } = data;
    if (applicants?.length > 0) {
      this.applicantData = applicants[0];
      console.log('申请人数据:', this.applicantData);
      this.setData({
        visaTitle: visaInfo.title,
        visaCity: visaInfo.city,
        templateIds: visaInfo.templateIds,
        userName: applicants[0].name,
        userType: applicants[0].identity.trim(),
        orderPrice: price || 0,
        contactPhone: applicants[0].phone || '',
        dates: [{
          city: cityInfo.city,
          date: `最早可约${cityInfo.date}`,
          options: ['近30天内指定日期前往', '近30天内任意日期前往', '近30天内无法前往'],
          selected: '近30天内任意日期前往'
        }]
      }, () => {
        if (this.data.templateIds?.length > 0) {
          this.fetchMaterialList();
        } else {
          wx.showToast({ title: '未获取到模板ID', icon: 'none' });
        }
      });
    }
  },

  async fetchMaterialList() {
    try {
      if (!Array.isArray(this.data.templateIds) || !this.data.templateIds.length) return;
      wx.showLoading({ title: '加载中...' });
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: 'https://visa.goldenholiday.com/api/miniapp/admin/material/fields/all',
          method: 'POST',
          data: this.data.templateIds,
          header: { 'content-type': 'application/json', 'token': wx.getStorageSync('token') },
          success: resolve,
          fail: reject
        });
      });

      if (res.data.code === 1 && Array.isArray(res.data.data)) {
        const forms = this.initializeForms(res.data.data);
        this.setData({
          electronicDocuments: forms.electronicDocuments,
          paperDocuments: forms.paperDocuments.map(doc => ({ ...doc, type: 'form' }))
        }, () => this.updateStatus());
      } else {
        wx.showToast({ title: res.data.msg || '获取材料配置失败', icon: 'none' });
      }
    } catch (err) {
      this.handleError('获取材料列表失败', err);
    } finally {
      wx.hideLoading();
    }
  },

  initializeForms(materials) {
    const materialGroups = materials.reduce((groups, field) => {
      const materialType = field.materialType;
      const materialCategory = field.materialCategory;
      const fieldGroup = field.fieldGroup?.trim() || '';
      const groupKey = `${materialType}_${fieldGroup}`;
      if (!groups[groupKey]) {
        groups[groupKey] = { materialType, materialCategory, fieldGroup, fields: [] };
      }
      const isRequired = field.required === 1 || field.required === 'true' || field.required === true;
      groups[groupKey].fields.push({
        name: field.fieldName,
        label: field.fieldLabel,
        type: field.fieldType,
        required: isRequired,
        description: field.description,
        options: field.fieldOptions ? JSON.parse(field.fieldOptions) : undefined,
        sortOrder: field.sortOrder,
        fieldGroup
      });
      return groups;
    }, {});

    const materialsArray = Object.values(materialGroups);
    const electronicDocuments = materialsArray
      .filter(item => item.materialCategory === 0 && (item.fieldGroup === this.data.userType || item.fieldGroup === '全部'))
      .map(item => ({
        id: `${item.materialType}_${item.fieldGroup}`,
        name: item.materialType,
        status: '待上传',
        statusClass: 'pending',
        description: '',
        formData: {},
        fields: item.fields,
        fieldGroup: item.fieldGroup,
        materialCategory: item.materialCategory
      }));

    const paperDocuments = materialsArray
      .filter(item => item.materialCategory === 1 && (item.fieldGroup === this.data.userType || item.fieldGroup === '全部'))
      .map(item => ({
        id: `${item.materialType}_${item.fieldGroup}`,
        name: item.materialType,
        status: '待填写',
        statusClass: 'pending',
        description: '',
        type: 'form',
        formData: {},
        fields: item.fields,
        fieldGroup: item.fieldGroup,
        materialCategory: item.materialCategory
      }));

    return { electronicDocuments, paperDocuments };
  },

  validateForm(form) {
    const missingFields = form.fields
      .filter(field => field.required && !form.formData?.[field.name])
      .map(field => field.label);
    return { isValid: missingFields.length === 0, missingFields };
  },

  updateFormStatus(formType, status) {
    this.setData({
      [`${formType}Status`]: status,
      [`${formType}StatusText`]: status === 'completed' ? '已完成' : formType === 'electronic' ? '待完成' : '待填写',
      [`${formType}StatusClass`]: status === 'completed' ? 'completed' : 'pending'
    }, () => this.updateStatus());
  },
  updateStatus() {
    const electronicCompleted = this.data.electronicDocuments.length > 0 &&
      this.data.electronicDocuments.every(doc => doc.status === '已完成');
    const paperCompleted = this.data.paperDocuments.length > 0 &&
      this.data.paperDocuments.every(doc => doc.status === '已完成');
    this.setData({
      electronicStatus: electronicCompleted ? 'completed' : 'pending',
      electronicStatusText: electronicCompleted ? '已完成' : '待完成',
      paperStatus: paperCompleted ? 'completed' : 'pending',
      paperStatusText: paperCompleted ? '已完成' : '待填写'
    });
  },

  validateAllForms() {
    const electronicIncomplete = this.data.electronicDocuments.some(doc => doc.status !== '已完成');
    const paperIncomplete = this.data.paperDocuments.some(doc => doc.status !== '已完成');
    return {
      isValid: !electronicIncomplete && !paperIncomplete,
      electronic: { isValid: !electronicIncomplete, message: electronicIncomplete ? '请完成所有电子资料' : '' },
      paper: { isValid: !paperIncomplete, message: paperIncomplete ? '请完成所有申请表' : '' }
    };
  },

  async handlePayment() {
    const app = getApp();
    if (!app.globalData.userInfo) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
    if (!app.globalData.userInfo.phone) {
      wx.showToast({ title: '请先绑定手机号', icon: 'none' });
      return;
    }
  
    wx.showLoading({ title: '正在支付...', mask: true });
    try {
      const orderNo = await this.createOrder();
      if (!orderNo) throw new Error('订单创建失败：未获取到订单号');
  
      await this.uploadAllFormData(orderNo); // 确保数据上传在支付之前完成
  
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: 'https://visa.goldenholiday.com/api/miniapp/admin/pay/payment',
          method: 'POST',
          header: { 'content-type': 'application/json', 'token': wx.getStorageSync('token') },
          data: { orderId: orderNo, userId: app.globalData.userInfo.id },
          success: resolve,
          fail: reject
        });
      });
  
      if (res.statusCode === 200 && res.data.code === 1) {
        const payData = res.data.data;
        await new Promise((resolve, reject) => {
          wx.requestPayment({
            timeStamp: payData.timeStamp,
            nonceStr: payData.nonceStr,
            package: payData.package,
            signType: payData.signType,
            paySign: payData.paySign,
            success: async () => {
              console.log('支付成功，更新订单状态为已支付');
              await this.updateOrderStatus(orderNo, '已支付');
              this.handlePaymentSuccess();
            },
            fail: async (err) => {
              console.log('支付失败或取消:', err);
              wx.showLoading({ title: '正在确认支付结果...', mask: true });
              let status = '';
              for (let i = 0; i < 5; i++) { // 最多轮询5次，每次1秒
                status = await queryOrderStatus(orderNo);
                if (status === '已支付') break;
                await sleep(1000);
              }
              wx.hideLoading();
              if (status === '已支付') {
                wx.showToast({ title: '支付成功', icon: 'success' });
                await this.updateOrderStatus(orderNo, '已支付');
                this.handlePaymentSuccess();
              } else {
                await this.updateOrderStatus(orderNo, '待支付');
                if (err.errMsg === 'requestPayment:fail cancel') {
                  wx.showToast({ title: '支付已取消', icon: 'none' });
                } else {
                  this.handleError('支付失败', err);
                }
                wx.switchTab({ url: '/pages/order/order' });
              }
            }
          });
        });
      } else {
        throw new Error(res.data.msg || '获取支付参数失败');
      }
    } catch (err) {
      this.handleError('支付失败', err);
    } finally {
      wx.hideLoading();
    }
  },

  async uploadImagesAndReplacePaths() {
    // 收集所有需要上传的本地图片路径及其表单位置
    const imageTasks = [];
    const docTypes = ['electronicDocuments', 'paperDocuments'];
    docTypes.forEach(docType => {
      this.data[docType].forEach((doc, docIndex) => {
        Object.entries(doc.formData).forEach(([fieldName, fieldValue]) => {
          if (Array.isArray(fieldValue)) {
            fieldValue.forEach((imgPath, imgIdx) => {
              // 修改判断条件，同时支持开发工具和真机的临时文件路径
              if (typeof imgPath === 'string' && (imgPath.startsWith('http://tmp/') || imgPath.startsWith('wxfile://tmp_'))) {
                imageTasks.push({ docType, docIndex, fieldName, imgIdx, imgPath });
              }
            });
          } else if (typeof fieldValue === 'string' && (fieldValue.startsWith('http://tmp/') || fieldValue.startsWith('wxfile://tmp_'))) {
            imageTasks.push({ docType, docIndex, fieldName, imgIdx: null, imgPath: fieldValue });
          }
        });
      });
    });
  
    // 上传所有图片并替换路径
    for (const task of imageTasks) {
      console.log('准备上传图片，本地路径：', task.imgPath); // 新增：打印上传前的本地路径
      const uploadRes = await new Promise((resolve, reject) => {
        wx.uploadFile({
          url: 'https://visa.goldenholiday.com/api/miniapp/admin/images/usermaterial/upload', // 你的图片上传接口
          filePath: task.imgPath,
          name: 'file',
          formData: {},
          header: { 'token': wx.getStorageSync('token') }, // 关键：加上 token
          success: res => {
            try {
              console.log('图片上传返回：', res.data); // 新增：打印后端返回内容
              const data = JSON.parse(res.data);
              if (data.code === 1 && data.data) { // 这里改为 data.data
                resolve(data.data);               // 这里改为 data.data
              } else {
                reject(new Error(data.msg || '图片上传失败'));
              }
            } catch (e) {
              reject(e);
            }
          },
          fail: reject
        });
      });
  
      // 替换本地路径为服务器路径
      const doc = this.data[task.docType][task.docIndex];
      if (task.imgIdx !== null) {
        doc.formData[task.fieldName][task.imgIdx] = uploadRes;
      } else {
        doc.formData[task.fieldName] = uploadRes;
      }
    }
    // 新增：同步回 this.data
    this.setData({
      electronicDocuments: this.data.electronicDocuments,
      paperDocuments: this.data.paperDocuments
    });
  },
  
  async updateOrderStatus(orderNo, orderStatus) {
    try {
      console.log(`更新订单状态: orderNo=${orderNo}, orderStatus=${orderStatus}`);
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: 'https://visa.goldenholiday.com/api/miniapp/admin/order/updateStatus',
          method: 'POST',
          header: { 'content-type': 'application/json', 'token': wx.getStorageSync('token') },
          data: { orderNo, orderStatus }, // 确保字段名称一致
          success: resolve,
          fail: (error) => {
            console.error('请求失败:', error);
            reject(error);
          }
        });
      });
  
      if (res.data.code !== 1) {
        console.error('更新订单状态失败:', res.data.msg);
        throw new Error(res.data.msg || '更新订单状态失败');
      } else {
        console.log('订单状态更新成功');
      }
    } catch (error) {
      console.error('更新订单状态错误:', error);
    }
  },

  async uploadAllFormData(orderId) {
    if (!orderId) throw new Error('订单号不能为空');
    const userId = getApp().globalData.userInfo.id;
    const allFormData = [];
  
    // 新增：先上传所有图片并替换路径
    await this.uploadImagesAndReplacePaths();
    this.data.electronicDocuments.forEach(doc => {
      Object.entries(doc.formData).forEach(([fieldName, fieldValue]) => {
        if (Array.isArray(fieldValue)) {
          fieldValue.forEach(value => {
            allFormData.push({
              orderId,
              userId,
              materialType: doc.name,
              fieldName,
              fieldValue: value,
              materialCategory: doc.materialCategory
            });
          });
        } else if (fieldValue) {
          allFormData.push({
            orderId,
            userId,
            materialType: doc.name,
            fieldName,
            fieldValue,
            materialCategory: doc.materialCategory // 添加 material_category 字段
          });
        }
      });
    });
  
    this.data.paperDocuments.forEach(doc => {
      Object.entries(doc.formData).forEach(([fieldName, fieldValue]) => {
        if (fieldValue) {
          allFormData.push({
            orderId,
            userId,
            materialType: doc.name,
            fieldName,
            fieldValue: String(fieldValue),
            materialCategory: doc.materialCategory // 添加 material_category 字段
          });
        }
      });
    });
  
    console.log('上传的表单数据:', allFormData); // 打印 allFormData 以验证数据
  
    if (allFormData.length === 0) throw new Error('没有需要上传的表单数据');
  
    const res = await new Promise((resolve, reject) => {
      wx.request({
        url: 'https://visa.goldenholiday.com/api/miniapp/admin/formUserMateri/upload',
        method: 'POST',
        header: { 'content-type': 'application/json', 'token': wx.getStorageSync('token') },
        data: allFormData,
        success: resolve,
        fail: reject
      });
    });
  
    if (res.data.code !== 1) throw new Error(res.data.msg || '表单数据上传失败');
  },

  async createOrder() {
    try {
      const userInfo = getApp().globalData.userInfo;
      const timestamp = new Date().getTime();
      const randomNum = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
      const orderNumber = `${timestamp}${userInfo.id}${randomNum}`;
      const currentTime = getLocalISOString();
  
      const orderData = {
        number: orderNumber,
        userId: userInfo.id,
        userName: this.data.userName,
        userType: this.data.userType,
        visaTitle: this.data.visaTitle,
        visaCity: this.data.visaCity,
        price: this.data.orderPrice,
        selectedDate: this.data.dates[0]?.selected || '',
        appointmentDate: this.data.dates[0]?.date?.replace('最早可约', '') || '',
        productName: this.data.visaTitle,
        orderAmount: this.data.orderPrice,
        amount: this.data.orderPrice,
        paymentMethod: '微信支付',
        orderStatus: '待支付',
        orderSource: '小程序',
        contactPerson: this.data.userName,
        contactPhone: userInfo.phone || '',
        customerName: userInfo.nickName, // 使用全局存储的微信名称
        orderTime: currentTime,
        createTime: currentTime,
        updateTime: currentTime
      };
  
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: 'https://visa.goldenholiday.com/api/miniapp/admin/order/upload',
          method: 'POST',
          header: { 'content-type': 'application/json', 'token': wx.getStorageSync('token') },
          data: orderData,
          success: resolve,
          fail: reject
        });
      });
  
      if (res.data.code === 1) return orderData.number;
      throw new Error(res.data.msg || '创建订单失败');
    } catch (error) {
      throw new Error('创建订单失败：' + error.message);
    }
  },

  handlePaymentSuccess() {
    wx.showToast({ title: '支付成功', icon: 'success', duration: 2000 });
    this.setData({ showOrderModal: false, showOtherPaymentModal: false });
    setTimeout(() => {
      try {
        wx.switchTab({ url: '/pages/order/order' });
      } catch (error) {
      }
    }, 2000);
  },

  handleOtherPayment() {
    this.setData({ showOtherPaymentModal: true });
  },

  hideOtherPaymentModal() {
    this.setData({ showOtherPaymentModal: false, showOrderModal: false });
  },

  onPaymentCodeInput(e) {
    this.setData({ paymentCode: e.detail.value });
  },

  confirmOtherPayment() {
    if (!this.data.paymentCode) {
      wx.showToast({ title: '请输入付款码', icon: 'none' });
      return;
    }
    wx.showLoading({ title: '验证中...', mask: true });
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({ title: '验证成功', icon: 'success', duration: 2000 });
      setTimeout(() => this.hideOtherPaymentModal(), 2000);
    }, 1500);
  },

  switchTab(e) {
    this.setData({ activeTab: e.currentTarget.dataset.tab });
  },

  handleImageUpload(e) {
    const { formIndex, fieldName } = e.currentTarget.dataset;
    if (formIndex < 0 || formIndex >= this.data.electronicDocuments.length) {
      console.error('Invalid form index:', formIndex);
      wx.showToast({ title: '上传失败，表单索引无效', icon: 'none' });
      return;
    }
  
    const form = this.data.electronicDocuments[formIndex];
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        // 直接替换而不是追加
        const formData = { ...form.formData, [fieldName]: tempFilePath };
        this.setData({ 
          [`electronicDocuments[${formIndex}].formData`]: formData 
        });
      }
    });
  },

  

  onFieldInput(e) {
    const { formIndex, fieldName } = e.currentTarget.dataset;
    const { activeTab } = this.data;
    const key = activeTab === 'electronic' ? 'electronicDocuments' : 'paperDocuments';
    console.log('表单输入:', { tab: activeTab, formIndex, fieldName, value: e.detail.value });
    this.setData({
      [`${key}[${formIndex}].formData.${fieldName}`]: e.detail.value
    }, () => {
      console.log('保存后的表单数据:', { formIndex, formData: this.data[key][formIndex].formData });
    });
  },

  handleFormSubmit(e) {
    const { formIndex } = e.currentTarget.dataset;
    const { activeTab } = this.data;
    const form = this.data[`${activeTab}Documents`][formIndex];
    console.log('提交表单数据:', { tab: activeTab, formIndex, formData: form.formData });

    const validation = this.validateForm(form);
    if (!validation.isValid) {
      wx.showToast({ title: `请填写：${validation.missingFields.join('、')}`, icon: 'none' });
      return;
    }

    this.setData({
      [`${activeTab}Documents[${formIndex}].status`]: '已完成',
      [`${activeTab}Documents[${formIndex}].statusClass`]: 'completed'
    }, () => {
      this.updateStatus();
      console.log('表单提交后状态:', {
        tab: activeTab,
        formIndex,
        status: this.data[`${activeTab}Documents`][formIndex].status,
        formData: this.data[`${activeTab}Documents`][formIndex].formData
      });
      wx.showToast({ title: '保存成功', icon: 'success' });
    });
  },

  onDateFieldChange(e) {
    const { formIndex, fieldName } = e.currentTarget.dataset;
    const { activeTab } = this.data;
    const key = activeTab === 'electronic' ? 'electronicDocuments' : 'paperDocuments';
    const selectedDate = e.detail.value;

    try {
      const form = this.data[key][formIndex];
      if (!form) return;
      const formData = { ...form.formData, [fieldName]: selectedDate };
      this.setData({ [`${key}[${formIndex}].formData`]: formData }, () => {
        this.checkAndUpdateFormStatus(activeTab, formIndex);
      });
    } catch (error) {
      wx.showToast({ title: '日期更新失败', icon: 'none' });
    }
  },

  onRadioChange(e) {
    const { formIndex, fieldName } = e.currentTarget.dataset;
    const { activeTab } = this.data;
    const key = activeTab === 'electronic' ? 'electronicDocuments' : 'paperDocuments';
    this.setData({ [`${key}[${formIndex}].formData.${fieldName}`]: e.detail.value });
  },

  checkAndUpdateFormStatus(formType, formIndex) {
    const form = this.data[`${formType}Documents`][formIndex];
    const validation = this.validateForm(form);
    this.setData({
      [`${formType}Documents[${formIndex}].status`]: validation.isValid ? '已完成' : '待完成',
      [`${formType}Documents[${formIndex}].statusClass`]: validation.isValid ? 'completed' : 'pending'
    }, () => this.updateStatus());
  },

  confirmOrder() {
    const validation = this.validateAllForms();
    if (!validation.electronic.isValid) {
      wx.showToast({ title: validation.electronic.message, icon: 'none' });
      return;
    }
    if (!validation.paper.isValid) {
      wx.showToast({ title: validation.paper.message, icon: 'none' });
      return;
    }
    if (!this.data.dates.length || !this.data.dates[0].selected) {
      wx.showToast({ title: '请选择赴馆日期', icon: 'none' });
      return;
    }
    this.setData({ showOrderModal: true }, () => {
      // 只在PC端弹窗扫码支付温馨提示
      const platform = wx.getSystemInfoSync().platform;
      if (platform === 'windows' || platform === 'mac' || platform === 'linux') {
        wx.showModal({
          title: '温馨提示',
          content: '扫码支付后，请耐心等待系统响应，切勿着急点击“取消”按钮。如已支付，请务必等待页面自动跳转或提示后再操作。',
          showCancel: false,
          confirmText: '我知道了'
        });
      }
    });
  },

  hideOrderModal() {
    this.setData({ showOrderModal: false });
  },

  handleError(message, error) {
    console.error(message, error);
    wx.showToast({ title: message, icon: 'none', duration: 2000 });
  },

  copyText(e) {
    const text = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: text,
      success: () => {
        wx.showToast({
          title: '复制成功',
          icon: 'success',
          duration: 1500
        });
      }
    });
  },

  // 添加联系客服方法
  contactSupport() {
    wx.navigateTo({
      url: '/pages/contactSupport/contactSupport' 
    });
  },
});
